<template>
	<view class="container">
		<contract-service />
		<!-- <movable-area class="movable-area">
	        <movable-view class="movable-view" :x="x" :y="y" direction="all">
	      
			  <button class="newProblem"  open-type="im"  :data-im-id="imId"  @im="imCallback"  @error="onimError">
			      <text>客服</text>
			    </button>
	        </movable-view>
	  </movable-area>
	  <movable-area class="movable-area1">
	        <movable-view class="movable-view" :x="x" :y="y" direction="all">
	  		<button class="newProblem"  @click="phoneclick">
	            <text>热线客服</text>
	          </button>
	        </movable-view>
	  </movable-area> -->
		<mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ native: true }"
			@down="downCallback" :up="upOption" @up="upCallback">
			<!-- tab栏 -->
			<u-tabs :list="tabs" :is-scroll="false" :current="curTab" active-color="#FA2209" :duration="0.2"
				@change="onChangeTab" />

			<!-- 订单列表 -->
			<view class="order-list">
				<view class="order-item" v-for="(item, index) in list.data" :key="index">
					<view class="item-top">
						<view class="item-top-right">
							<text class="state-text">{{ item.state_text }}</text>
							<!-- <text class="state-text">{{ item.State }}</text> -->
						</view>
						<view class="item-top-left">
							<text class="order-time">{{ item.create_time }}</text>
							<!-- <text class="order-time">{{ item.ServiceTime }}</text> -->
						</view>
					</view>
					<!-- 商品列表 -->
					<view class="goods-list" @click="handleTargetDetail(item.order_id)">
						<view class="goods-item" v-for="(goods, idx) in item.goods" :key="idx">
							<!-- 商品图片 -->
							<view class="goods-image">
								<image class="image" :src="goods.goods_image" mode="aspectFill"></image>
							</view>
							<!-- 商品信息 -->
							<view class="goods-wraper">
								<view class="goods-basic">
									<view class="goods-content">
										<view class="goods-title"><text class="twoline-hide">{{
                        goods.goods_name
                      }}</text></view>
										<view class="goods-props clearfix">
											<view class="goods-props-item" v-for="(props, idx) in goods.goods_props"
												:key="idx">
												<text>{{ props.value.name }}</text>
											</view>
										</view>
									</view>
									<view class="goods-trade">
										<view class="goods-price">
											<text class="unit">￥</text>
											<text class="value">{{
                        goods.is_user_grade
                          ? goods.grade_goods_price
                          : goods.goods_price
                      }}</text>
										</view>
										<view class="goods-num">
											<text>×{{ goods.total_num }}</text>
										</view>
									</view>
								</view>
								<view class="goods-footer">
									<view class="order-total">
										<!-- <text>共{{ item.total_num }}件商品，总金额</text> -->
										<text>总金额</text>
										<text class="unit">￥</text>
										<text class="money">{{ item.pay_price }}</text>
									</view>
								</view>
							</view>
							<!-- 交易信息 -->
						</view>
					</view>
					<!-- 订单合计 -->

					<!-- 订单操作 -->
					<view v-if="item.order_status != OrderStatusEnum.CANCELLED.value" class="order-handle">
						<view class="btn-group clearfix">
							<!-- 退款完成 无操作 -->
							<block v-if="item.order_status == OrderStatusEnum.REFUNDED.value">
							</block>
							<!-- 未支付取消订单 -->
							<block v-else-if="item.pay_status == PayStatusEnum.PENDING.value">
								<view class="btn-item" @click="onCancel(item.order_id)">取消</view>
							</block>

							<!-- 未支付的订单 -->
							<block v-if="
                  OrderStatusEnum.NORMAL.value == item.order_status &&
                  item.pay_status == PayStatusEnum.PENDING.value
                ">
								<view class="btn-item active" @click.stop="onPay(item)">立即支付</view>
							</block>
							<!-- 已预约 -->
							<block v-if="
                  OrderStatusEnum.NORMAL.value == item.order_status &&
                  item.delivery_status1 ==
                    DeliveryStatusEnum.NOT_DELIVERED.value
                ">
								<view v-if="item.pay_status == PayStatusEnum.SUCCESS.value" class="btn-item active"
									@click="handleYuyue(item.order_id)">立即预约</view>
							</block>
							<!-- 已预约 -->
							<block v-else-if="
                  [OrderStatusEnum.NORMAL.value].includes(item.order_status)
                ">
								<view class="yiyuyue" v-if="
                    item.delivery_status ==
                      DeliveryStatusEnum.NOT_DELIVERED.value &&
                    item.delivery_status1 != DeliveryStatusEnum.RECEIVED.value
                  ">服务时间：{{ item.service_time.substr(0, 16) }}</view>
								<!-- <view
                  class="yiyuyue"
                  v-else-if="
                    item.delivery_status1 == DeliveryStatusEnum.PAYED.value
                  "
                  >已服务</view
                > -->
							</block>

							<!-- 已支付进行中的订单 -->
							<block v-if="
                  [OrderStatusEnum.NORMAL.value].includes(item.order_status)
                ">
								<block v-if="
                    item.pay_status == PayStatusEnum.SUCCESS.value &&
					item.delivery_status1==DeliveryStatusEnum.NOT_DELIVERED.value">
									<view class="btn-item" @click.stop="handleApplyRefund(item)">申请退款</view>
								</block>
							</block>
							<!-- 已申请取消 -->
							<!-- <view v-else class="f-28 col-8">取消申请中</view> -->
							<!-- 确认收货 -->
							<block v-if="
                  [
                    OrderStatusEnum.NORMAL.value,
                    OrderStatusEnum.COMPLETED.value,
                  ].includes(item.order_status) &&
                  item.delivery_status1 == DeliveryStatusEnum.RECEIVED.value
                ">
								<!-- <view class="btn-item active" @click="onReceipt(item)"
                  >完成服务
                </view> -->

								<!-- <rate-button :order-id="item.douyin_order_id" @init="handleInit" @error="handleError"
									@success="handleSuccess" /> -->
							</block>
							<!-- 订单评价 -->
							<block v-if="item.delivery_status1 == DeliveryStatusEnum.PAYED.value">
								<!-- <view class="yiyuyue">服务已完成 </view> -->
							</block>
						</view>
					</view>
				</view>
			</view>
		</mescroll-body>

		<!-- 支付方式弹窗 -->
		<u-popup v-model="showPayPopup" mode="bottom" border-radius="26" :closeable="true">
			<view class="pay-popup">
				<view class="title">请选择支付方式</view>
				<view class="pop-content">
					<!-- 微信支付 -->
					<!-- #ifdef MP-WEIXIN -->
					<view class="pay-item dis-flex flex-x-between" @click="onSelectPayType(PayTypeEnum.WECHAT.value)">
						<view class="item-left dis-flex flex-y-center">
							<view class="item-left_icon wechat">
								<text class="iconfont icon-wechat-pay"></text>
							</view>
							<view class="item-left_text">
								<text>{{ PayTypeEnum.WECHAT.name }}</text>
							</view>
						</view>
					</view>
					<!-- #endif -->
					<!-- 余额支付 -->
					<view class="pay-item dis-flex flex-x-between" @click="onSelectPayType(PayTypeEnum.BALANCE.value)">
						<view class="item-left dis-flex flex-y-center">
							<view class="item-left_icon balance">
								<text class="iconfont icon-balance-pay"></text>
							</view>
							<view class="item-left_text">
								<text>{{ PayTypeEnum.BALANCE.name }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		DeliveryStatusEnum,
		DeliveryTypeEnum,
		OrderStatusEnum,
		PayStatusEnum,
		PayTypeEnum,
		ReceiptStatusEnum,
	} from "@/common/enum/order";
	import * as CheckoutApi from "@/api/checkout";
	import MescrollBody from "@/components/mescroll-uni/mescroll-body.vue";
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
	import {
		getEmptyPaginateObj,
		getMoreListData
	} from "@/core/app";
	import * as OrderApi from "@/api/order";
	import {
		wxPayment
	} from "@/core/app";

	// 每页记录数量
	const pageSize = 15;

	// tab栏数据
	const tabs = [{
			name: `全部`,
			value: "all",
		},
		{
			name: `待支付`,
			value: "payment",
		},
		{
			name: `待服务`,
			value: "delivery",
		},
		{
			name: `已完成`,
			value: "received",
		},
		{
			name: `待评价`,
			value: "comment",
		},
	];

	export default {
		components: {
			MescrollBody,
		},
		mixins: [MescrollMixin],
		data() {
			return {
				// 枚举类
				DeliveryStatusEnum,
				DeliveryTypeEnum,
				OrderStatusEnum,
				PayStatusEnum,
				PayTypeEnum,
				ReceiptStatusEnum,

				// 当前页面参数
				options: {
					dataType: "all",
				},
				// tab栏数据
				tabs,
				// 当前标签索引
				curTab: 0,
				// 订单列表数据
				list: getEmptyPaginateObj(),

				// 上拉加载配置
				upOption: {
					// 首次自动执行
					auto: true,
					// 每页数据的数量; 默认10
					page: {
						size: pageSize,
					},
					// 数量要大于4条才显示无更多数据
					noMoreSize: 4,
					// 空布局
					empty: {
						tip: "亲，暂无订单记录",
					},
				},
				// 控制首次触发onShow事件时不刷新列表
				canReset: false,
				// 支付方式弹窗
				showPayPopup: false,
				imId: "hjm616161",
			};
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// 初始化当前选中的标签
			this.initCurTab(options);

			if (tt.canIUse("industrySDK.pay-button")) {
				console.log("支持pay-button组件");
			} else {
				console.log("不支持pay-button组件");
			}
		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			this.canReset = true;
			this.canReset && this.onRefreshList();
		},

		methods: {
			handleInit(event) {
				console.log(event, 111222)
			},
			handleSuccess() {

			},
			handleError(event) {
				const {
					errMsg,
					errNo
				} = event.detail;
				console.error(errMsg, errNo)
			},

			imCallback(e) {
				console.log("跳转IM客服成功", e.detail);
			},
			onimError(e) {
				console.log("拉起IM客服失败", e.detail);
			},
			// 初始化当前选中的标签
			initCurTab(options) {
				const app = this;
				if (options.dataType) {
					const index = app.tabs.findIndex(
						(item) => item.value == options.dataType
					);
					app.curTab = index > -1 ? index : 0;
				}
			},
			phoneclick() {
				tt.makePhoneCall({
					phoneNumber: "4009673811",
					success: function() {
						tt.showToast({
							title: "success",
						});
					},

					fail(err) {
						// tt.showToast({
						//   icon: 'none',
						//   title: err.errMsg
						// });
						console.log(err.errMsg);
					},
				});
			},

			/**
			 * 上拉加载的回调 (页面初始化时也会执行一次)
			 * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
			 * @param {Object} page
			 */
			upCallback(page) {
				const app = this;
				// 设置列表数据
				app
					.getOrderList(page.num)
					.then((list) => {
						const curPageLen = list.data.length;
						const totalSize = list.data.total;
						app.mescroll.endBySize(curPageLen, totalSize);
					})
					.catch(() => app.mescroll.endErr());
			},

			// 获取订单列表
			getOrderList(pageNo = 1) {
				const app = this;
				return new Promise((resolve, reject) => {
					OrderApi.list({
						dataType: app.getTabValue(),
						page: pageNo,
					}, {
						load: false,
					}).then((result) => {
						// 合并新数据
						console.log(result.data.list);
						const newList = app.initList(result.data.list);
						app.list.data = getMoreListData(newList, app.list, pageNo);
						resolve(newList);
					});
				});
			},

			// 初始化订单列表数据
			initList(newList) {
				newList.data.forEach((item) => {
					item.total_num = 0;
					// item.goods.forEach(goods => {
					//   item.total_num += goods.total_num
					// })
				});
				return newList;
			},

			// 获取当前标签项的值
			getTabValue() {
				return this.tabs[this.curTab].value;
			},

			// 切换标签项
			onChangeTab(index) {
				const app = this;
				// 设置当前选中的标签
				app.curTab = index;
				// 刷新订单列表
				app.onRefreshList();
			},

			// 刷新订单列表
			onRefreshList() {
				// this.list = getEmptyPaginateObj()
				setTimeout(() => {
					this.mescroll.resetUpScroll();
				}, 120);
			},

			// 取消订单
			onCancel(orderId) {
				const app = this;
				uni.showModal({
					title: "友情提示",
					content: "确认要取消该订单吗？",
					success(o) {
						if (o.confirm) {
							OrderApi.cancel(orderId).then((result) => {
								// 显示成功信息
								app.$toast(result.message);
								// 刷新订单列表
								app.onRefreshList();
							});
						}
					},
				});
			},
			// 跳转到申请售后页面
			handleApplyRefund(order) {
				const orderGoodsId = order.goods[0].order_goods_id;
				this.$navTo("pages/refund/apply", {
					orderGoodsId,
				});
			},
			onRefund(orderId) {
				const app = this;

				// this.$navTo('pages/order/detail', {
				// 	orderId
				// })
				uni.showModal({
					title: "友情提示",
					content: "确认要退款吗？",
					success(o) {
						if (o.confirm) {
							OrderApi.refund(orderId).then((result) => {
								// 显示成功信息
								app.$toast(result.message);
								// 刷新订单列表
								app.onRefreshList();
							});
						}
					},
				});
			},

			// 确认收货
			onReceipt(order) {
				const app = this;
				const confirm = tt.canIUse("confirmFulfillment");
				console.info("can i use confirm", confirm, order.douyin_certificate_id);
				tt.confirmFulfillment({
					orderId: order.douyin_order_id,
					itemOrderIdList: order.douyin_order_item_id.split(","),
					toStatus: "fulfill_done",
					serviceId: order.douyin_delivery_id,
					success(res) {
						console.log("success执行了", res);
						OrderApi.receipt(order.order_id).then((result) => {
							// 显示成功信息
							app.$success(result.message);
							// 刷新订单列表
							app.onRefreshList();
						});
					},
					fail(err) {
						console.log("fail执行了", err);
					},
				});
				// uni.showModal({
				//   title: "友情提示",
				//   content: "确认完成服务了吗？",
				//   success(o) {
				//     if (o.confirm) {
				//       OrderApi.receipt(orderId).then((result) => {
				//         // 显示成功信息
				//         app.$success(result.message);
				//         // 刷新订单列表
				//         app.onRefreshList();
				//       });
				//     }
				//   },
				// });
			},

			// 点击去支付
			onPay(data) {
				const app = this;
				// 记录订单id
				//this.payOrderId = orderId
				// 显示支付方式弹窗
				//this.showPayPopup = true
				if (!data.douyin_order_id)
					return app.$error("订单未创建成功，请重新下单");
				let canPay = tt.canIUse("continueToPay");
				//console.log(canPay);
				tt.continueToPay({
					orderId: data.douyin_order_id,
					//outOrderNo: data.order_id,
					success(res) {
						const {
							orderId,
							outOrderNo
						} = res;
						console.log("success res", res);
						console.log("orderId", orderId, "outOrderNo", outOrderNo);
						CheckoutApi.query({
							orderId: data.order_id
						});
						app.navToCurOrder(data.order_id);
						return app.$error("支付成功");
					},
					fail(res) {
						const {
							orderId,
							outOrderNo,
							errNo,
							errMsg,
							errLogId
						} = res;
						//console.log("失败:",res);
						if (errLogId) {
							console.log("查询订单信息失败", errNo, errMsg, errLogId);
							return app.$error(errMsg);
						}
						if (orderId || outOrderNo) {
							console.log("支付失败", errNo, errMsg, orderId, outOrderNo);
							return app.$error("支付失败");
						}
					},
				});
			},
			navToCurOrder(orderId) {
				setTimeout(() => {
					this.$navTo("pages/order/detail", {
						orderId,
					});
				}, 1000);
			},
			// 选择支付方式
			onSelectPayType(payType) {
				const app = this;
				// 隐藏支付方式弹窗
				this.showPayPopup = false;
				// 发起支付请求
				OrderApi.pay(app.payOrderId, payType).then((result) =>
					app.onSubmitCallback(result)
				);
			},

			// 订单提交成功后回调
			onSubmitCallback(result) {
				const app = this;
				// 发起微信支付
				if (result.data.pay_type == PayTypeEnum.WECHAT.value) {
					wxPayment(result.data.payment)
						.then(() => {
							app.$success("支付成功");
							setTimeout(() => {
								app.onRefreshList();
							}, 1500);
						})
						.catch((err) => {
							app.$error("订单未支付");
						})
						.finally(() => {
							app.disabled = false;
						});
				}
				// 余额支付
				if (result.data.pay_type == PayTypeEnum.BALANCE.value) {
					app.$success("支付成功");
					app.disabled = false;
					setTimeout(() => {
						app.onRefreshList();
					}, 1500);
				}
			},

			// 跳转到订单详情页
			handleTargetDetail(orderId) {
				this.$navTo("pages/order/detail", {
					orderId,
				});
			},

			// 跳转到订单评价页
			handleTargetComment(orderId) {
				this.$navTo("pages/order/comment/index", {
					orderId,
				});
			},
			handleYuyue(orderId) {
				this.$navTo("pages/order/yuyue", {
					orderId,
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	// 项目内容
	.order-item {
		margin: 20rpx auto 20rpx auto;
		padding: 20rpx 20rpx;
		width: 94%;
		box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
		border-radius: 16rpx;
		background: #fff;
	}

	// 项目顶部
	.item-top {
		display: flex;
		justify-content: space-between;
		font-size: 30rpx;
		margin-bottom: 30rpx;

		.order-time {
			color: #777;
		}

		.state-text {
			color: $uni-text-color-active;
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	// 商品列表
	.goods-list {

		// 商品项
		.goods-item {
			display: flex;
			margin-bottom: 40rpx;

			// 商品图片
			.goods-image {
				width: 180rpx;
				height: 180rpx;

				.image {
					display: block;
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}
			}

			.goods-wraper {
				display: flex;
				flex: 1;
				flex-direction: column;
				justify-content: space-between;
				padding-left: 10rpx;

				.goods-basic {
					display: flex;
					justify-content: space-between;
				}

				.goods-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;
					flex-direction: row;
				}
			}

			// 商品内容
			.goods-content {
				.goods-title {
					font-size: 30rpx;
				}

				.goods-props {
					margin-top: 14rpx;
					color: #ababab;
					font-size: 30rpx;

					.goods-props-item {
						display: inline-block;
						margin-right: 14rpx;
						padding: 4rpx 16rpx;
						border-radius: 12rpx;
						background-color: #f5f5f5;
						width: auto;
					}
				}
			}

			// 交易信息
			.goods-trade {
				width: 150rpx;
				text-align: right;
				color: $uni-text-color-grey;
				font-size: 30rpx;

				.goods-price {
					vertical-align: bottom;
					margin-bottom: 16rpx;

					.unit {
						margin-right: -2rpx;
						font-size: 24rpx;
					}
				}
			}
		}
	}

	// 订单合计
	.order-total {
		font-size: 30rpx;
		vertical-align: bottom;
		text-align: right;

		.unit {
			margin-left: 8rpx;
			margin-right: -2rpx;
			font-size: 26rpx;
		}

		.money {
			font-size: 28rpx;
		}
	}

	// 订单操作
	.order-handle {
		.btn-group {
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.yiyuyue {
				margin-right: 0rpx;
				color: #f00;
				font-weight: normal;
				font-size: 30rpx;
			}

			.btn-item {
				border-radius: 10rpx;
				padding: 6rpx 20rpx;
				margin-right: 30rpx;
				font-size: 35rpx;

				color: #383838;
				border: 1rpx solid #a8a8a8;

				&:last-child {
					margin-right: 0;
				}

				&.active {
					color: $uni-text-color-active;
					border: 1rpx solid $uni-text-color-active;
				}
			}
		}
	}

	// 弹出层-支付方式
	.pay-popup {
		padding: 24rpx;

		.title {
			font-size: 30rpx;
			margin-bottom: 40rpx;
			font-weight: bold;
			text-align: center;
		}

		.pop-content {
			min-height: 260rpx;
			padding: 0 10rpx;

			.pay-item {
				padding: 24rpx 35rpx;
				font-size: 28rpx;
				border-bottom: 1rpx solid #f1f1f1;

				&:last-child {
					border-bottom: none;
				}

				.item-left_icon {
					margin-right: 20rpx;
					font-size: 32rpx;

					&.wechat {
						color: #00c800;
					}

					&.balance {
						color: #ff9700;
					}
				}
			}
		}
	}

	.action-btn {
		min-width: 152rpx;
		height: 56rpx;
		padding: 0 30rpx;
		line-height: 56rpx;
		background-color: #fff;
		text-align: center;
		border-radius: 28rpx;
		border-color: rgb(102, 102, 102);
		cursor: pointer;
		user-select: none;
		color: #c7a157;
	}
</style>